import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'

export class ApiError extends Error {
  constructor(message, status, code) {
    super(message)
    this.name = 'ApiError'
    this.status = status
    this.code = code
  }
}

export const handleError = (error) => {
  if (error instanceof ApiError) {
    ElMessage.error(error.message)
  } else if (error.response) {
    const status = error.response.status
    const message = error.response.data?.message || '请求失败'
    
    switch (status) {
      case 400:
        ElMessage.error(`请求参数错误: ${message}`)
        break
      case 401:
        const userStore = useUserStore()
        userStore.logout()
        window.location.href = '/login'
        break
      case 403:
        ElMessage.error('没有权限执行此操作')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 500:
        ElMessage.error('服务器错误')
        break
      default:
        ElMessage.error(`请求失败: ${message}`)
    }
  } else if (error.request) {
    ElMessage.error('网络错误，请检查您的网络连接')
  } else {
    ElMessage.error('发生未知错误')
    console.error('Error:', error)
  }
  return Promise.reject(error)
}
